package ru.urfc.portal.ui.portlets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.urfc.portal.dao.Pair;
import ru.urfc.portal.exceptions.InternalException;
import ru.urfc.portal.managers.ClientManager;
import ru.urfc.portal.managers.impl.ClientManagerImpl;
import ru.urfc.portal.model.admins.User;
import ru.urfc.portal.security.PortalUserManager;
import ru.urfc.portal.ui.client.Constants;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

public class BasePortlet extends GenericPortlet implements Constants {
	
	ClientManager clientManager;
	
	PortalUserManager portalUserManager;
	
	private String googletName;

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	public static class JNDILookupException extends InternalException {
		public JNDILookupException(Throwable cause, String message) {
			super(cause, message);
		}
	}
	
	public void init() throws PortletException {
		googletName = "" + getInitParameter("googlet-name");
		try {
			clientManager = lookup(ClientManagerImpl.class);
			portalUserManager = lookup(PortalUserManager.class);
		} catch (NamingException e) {
			throw new JNDILookupException(e, e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	private <T> T lookup(Class<T> klass) throws NamingException {
		return (T)InitialContext.doLookup("java:module/" + klass.getSimpleName());
	}	
	
	public static class Parameter extends Pair<String, String> {
		public Parameter(String first, String second) {
			super(first, second);
		}
	}
	
	@Override
	protected void doView(RenderRequest request, RenderResponse response) throws PortletException,
			IOException {
		PrintWriter writer = response.getWriter();
		writer.write("<div class=\"googlet\"");
		for (Parameter parameter: getParameters(request)) {
			writer.write(MessageFormat.format(" {0}=\"{1}\"", parameter.getFirst(), parameter.getSecond()));
		}
		writer.write("></div>");
	}
	
	public List<Parameter> getParameters(RenderRequest request) {
		List<Parameter> result = new ArrayList<Parameter>();
		result.add(new Parameter(GOOGLET_PARAMETER_NAME, getGoogletName()));
		return result;
	}

	public String getGoogletName() {
		return googletName;
	}
	
	public User getUser(RenderRequest request) {
		String userEmail = getEmail(request);
		return clientManager.getUserByEmailAndActivate(userEmail);
	}

	public String getEmail(RenderRequest request) {
		String userId = request.getRemoteUser();
		return portalUserManager.emailFromId(userId);
	}
	
}
